package com.ly.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ly.common.Result;
import com.ly.common.StatusEnum;
import com.ly.dao.UserDao;
import com.ly.entity.User;
import com.ly.exp.ServiceException;
import com.ly.rep.PageRequest;
import com.ly.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
    @Resource
    public UserService userService;
    @Resource
    public UserDao userDao;

    @PostMapping("/page")
    @ApiOperation(value = "用户列表")
    public Result<?> page(@RequestBody PageRequest<User> pageRequest){
        PageInfo<User> pageList = userService.page(pageRequest);
        return  new Result<>(pageList,StatusEnum.SUCCESS);
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "用户新增或修改")
    public Result<?> saveOrUpdate(@RequestBody User user){
        if(user.getId() == null){
            user.setPassword(DigestUtil.md5Hex("123456"));
            userDao.insert(user);
        }else{
            userDao.updateById(user);
        }
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "用户的单个删除")
    public Result<?> delById(@PathVariable("id") Integer id){
        User user = userDao.selectById(id);
        if(Objects.isNull(user)){
            throw new ServiceException(StatusEnum.ERROR.getCode(), "用户不存在无法删除");
        }
        userDao.deleteById(id);
        return  new Result<>(StatusEnum.SUCCESS);
    }

    @PostMapping("/delBatchByIds")
    @ApiOperation(value = "用户批量删除")
    public Result<?> delBatchByIds(@RequestBody List<Integer> ids){
        userDao.delBatchByIds(ids);
        return  new Result<>(StatusEnum.SUCCESS);
    }
}
